/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.etu.upload;

import java.util.HashMap;
import java.util.Map;

/**
 *简单的转换器，把key=value;key:value转换为Map &lt;String,String &gt;
 */

public class ParameterParser {
	
	private char[] chars;
	
	private int p1;
	
	private int p2;
	
	private int len;
	
	private void parse(Map<String, String> map, char separator) {
		int p;
		for(p=p1;p<p2;p++){
			if(chars[p]==separator){
				parse(map,p);
				break;
			}
		}
		
	}

	private String mytrim(int p1,int p2) {
		int p=p1;
		StringBuilder sb=new StringBuilder();
		for(;p<p2;p++){
			if(chars[p]=='"'){continue;}
			sb.append(chars[p]);
		}
		return sb.toString();
	}

	/**
	 * 解析出header；
	 * @return Map<String,String>
	 * */
	public Map<String,String> parse(final String str,char[] separator){
		Map<String,String> map=new HashMap<String,String>();
		if(str==null||str.length()<2){
			return map;
		}
		str.trim();
		for(char c:separator){
			map.putAll(parse(str,c));
		}
		
		return map;
		}
	
	public Map<String,String> parse(final String str,char separator){
		Map<String,String> map=new HashMap<String,String>();
		if(str==null||str.length()<2){
			return map;
		}
		str.trim();
		chars=str.toCharArray();
		
		len=chars.length;
		
		p1=p2=0;
		int p=0;
		while(p2<len){
			if(chars[p2]==separator){
				p=p2;
			}
			if(chars[p2]==';'||chars[p2]=='\n'||chars[p2]=='\r'){
				if(p2-p1>2&&p>p1){
					parse(map,p);
					p=0;
				}
				p1=p2+1;
			}
			p2++;
		}
		p2--;
		parse(map,separator);
		
		return map;
		}

	private void parse(Map<String, String> map, int p) {
		
		String name;
		String value;

		name=(mytrim(p1,p)).trim();
		value=mytrim(p+1,p2).trim();
		
		map.put(name,value);
			
		
	}
}
